package com.gavin.plugin.database.optimize;

import org.slf4j.Logger;

import com.gavin.model.Model;
import com.gavin.model.Request;
import com.gavin.plugin.database.help.ValueUtils;
import com.gavin.plugin.database.optimize.parse.AnalyzedSQL;
import com.gavin.schema.dataservice.Log;
import com.gavin.schema.dataservice.type.LogLevelType;

public class TransLog {
	public static void onSQLStatement(Logger log,int hashCode, String strSQL) {
		if (log.isDebugEnabled()) {
			log.debug("Database connection " + hashCode+ ": " + strSQL);
		}
	}

	public static void onSQLExecuted(Logger log,int hashCode, String strSQL, long lSQLTime) {
		if (log.isInfoEnabled() == false) {
			return;
		}
		String strSQLTime = "(";
		if (lSQLTime >= 1000) {
			strSQLTime += "5level slow trans ";
		} else if (lSQLTime >= 500) {
			strSQLTime += "4level slow trans ";
		} else if (lSQLTime >= 300) {
			strSQLTime += "3level slow trans ";
		} else if (lSQLTime >= 100) {
			strSQLTime += "2level slow trans ";
		} else if (lSQLTime >= 50) {
			strSQLTime += "1level slow trans ";
		}
		strSQLTime += lSQLTime + "ms)";
		log.info("Database connection " + hashCode + " SQL executed " + strSQLTime + ": " + strSQL);
	}

	public static void callOnSQLStatement(Logger log,Model modelRequest, int hashCode, String strSQL) {
		if (!modelRequest.exists(Request.PRINT_GAVIN_TRANS_LOG)) {
			return;
		}
		String strRealSQL = AnalyzedSQL.getRealSQL(modelRequest, strSQL);
		onSQLStatement( log,hashCode, strRealSQL);
	}

	public static void callOnSQLExecuted(Logger log,Model modelRequest, int hashCode, String strSQL, long lSQLTime) {
		if (!modelRequest.exists(Request.PRINT_GAVIN_TRANS_LOG)) {
			return;
		}
		String strRealSQL = AnalyzedSQL.getRealSQL(modelRequest, strSQL);
		onSQLExecuted(log,hashCode, strRealSQL, lSQLTime);
	}

	public static void onException(Logger log,String strText, Model modelRequest, Exception e) {
		StringBuilder strbOutput = new StringBuilder(strText);
		if (modelRequest != null) {
			strbOutput.append("\r\n").append(modelRequest.toXML());
		}
		onException(log,strbOutput.toString(), e);
	}

	public static void onException(Logger log,String strText, Exception e) {
		log.error("Database Exception: " + strText + "\r\n" + e.getLocalizedMessage(), e);
	}
	
	public static void handleLog(Logger logger,Log log, Model modelRequest, Model modelResponse) {
		String strText = log.getText();
		strText = ValueUtils.getModelText(modelRequest, modelResponse, strText);

		if (log.getLevel().getType() == LogLevelType.DEBUG_TYPE) {
			logger.debug(strText);
		} else if (log.getLevel().getType() == LogLevelType.INFO_TYPE) {
			logger.info(strText);
		} else if (log.getLevel().getType() == LogLevelType.WARN_TYPE) {
			logger.warn(strText);
		} else if (log.getLevel().getType() == LogLevelType.ERROR_TYPE) {
			logger.error(strText);
		}
	}
	
}
